package jp.co.cos.ittrick.channel.controller;

import jp.co.cos.ittrick.channel.model.FileModel;
import jp.co.cos.ittrick.channel.service.FileService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

/**
 * <pre>
 * ファイルコントロール
 * アクセス例：/files?key=/aaa/bbb/ccc&w=200&h=300
 * </pre>
 * @author takahara
 *
 */
public class FilesController extends Controller {

	private FileService service = new FileService();

    @Override
    public Navigation run() {

    	String pkKey = asString("key");

    	if(pkKey == null || pkKey.equals("")) {
    	    return null;
    	}

    	String width = asString("w");
    	String height = asString("h");
    	FileModel data = service.getData(Integer.valueOf(pkKey));

    	if(data == null) {
    	    return null;
    	}

    	// バイトの取得
        byte[] imageBytes = service.getBytes(data);


        // リサイズする場合
        if(width != null && height != null) {

        	int w = Integer.valueOf(width);
        	int h = Integer.valueOf(height);

        	ImagesService imagesService = ImagesServiceFactory.getImagesService();
        	Image oldImage = ImagesServiceFactory.makeImage(imageBytes);
        	Transform resize = ImagesServiceFactory.makeResize(w, h);
        	Image newImage = imagesService.applyTransform(resize, oldImage);

        	// レスポンスを返す
        	show(data.getFileName(), newImage.getImageData());


        // リサイズしない場合
        } else {
        	show(data.getFileName(), imageBytes);

        }

        return null;
    }
}
